from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from datetime import date, timedelta

from apps.goods.models import GoodsVisitCount
from apps.orders.models import OrderInfo
from apps.users.models import User


# 用户总数
class UserTotalCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取所有用户总数
        count = User.objects.filter(is_staff=False).count()
        return Response({
            'count': count,
            'date': now_date
        })


# 日增长量
class UserDayCountView(APIView):
    def get(self, request):
        now_day = date.today()
        counts = User.objects.filter(date_joined__gte=now_day).count()
        return Response({
            'count': counts,
            'date': now_day
        })


# 日活跃度
class UserActiveCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取当日登录用户数量  last_login记录最后登录时间
        count = User.objects.filter(last_login__gte=now_date).count()
        return Response({
            "count": count,
            "date": now_date
        })


# 日下单用户量
class UserOrderCountView(APIView):
    def get(self, request):
        now_date = date.today()
        ordercounts = User.objects.filter(orders__create_time__gte=now_date).distinct().count()
        return Response({
            'count': ordercounts,
            'date': now_date
        })


# 月增用户
class UserMonthCountView(APIView):
    def get(self, request):
        now_day = date.today()

        data = []
        for i in range(29, -1, -1):
            #               日期之间运算
            now = now_day - timedelta(i)
            count = User.objects.filter(is_staff=False, date_joined__gte=now,
                                        date_joined__lt=now + timedelta(1)).count()
            data.append({
                'count': count,
                'date': now
            })

        return Response(data)


#日分类商品统计
class GoodsDayView(APIView):
    def get(self,request):
        now_today=date.today()
        visit=GoodsVisitCount.objects.filter(date=now_today)

        data=[]
        for i in visit:
            data.append({
                "category":i.category.name,
                "count": i.count
            })
        return Response(data)